package com.athuiju.fenxiaoback.controller.front;


import com.athuiju.fenxiaoback.entity.*;
import com.athuiju.fenxiaoback.entity.vo.*;
import com.athuiju.fenxiaoback.service.*;
import com.athuiju.fenxiaoback.utils.JwtUtils;
import com.athuiju.fenxiaoback.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ExecutionException;

@Api(description = "订单",tags = "订单")
//@CrossOrigin
@RestController
@RequestMapping("/fenxiaoback/oms-order")
public class OrderFrontController {

    @Autowired
    private TbOrderService orderService;

    @Autowired
    OmsOrderService omsOrderService;

    @Autowired
    OmsOrderItemService omsOrderItemService;

    @Autowired
    PmsSkuSaleParamValueService skuSaleParamValueService;

    //点击结算确认订单
    @ApiOperation(value = "查看订单详情---根据orderNo")
    @GetMapping("/searchOrderDetailByOrderNo/{orderNo}")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OmsOrder.class),
    })
    public R searchOrderDetailByOrderNo(@PathVariable("orderNo") String orderNo,HttpServletRequest request) throws ExecutionException, InterruptedException {
        if (StringUtils.isEmpty(orderNo)){
            return R.error().put("msg","订单号不能为空");
        }

        String memberid = JwtUtils.getMemberIdByJwtToken(request);

        //1.查询订单
        OmsOrder omsOrder = omsOrderService.getOne(new QueryWrapper<OmsOrder>().eq("order_sn", orderNo));



        //2.1根据订单id获取订单项
        QueryWrapper<OmsOrderItem> itemWrapper=new QueryWrapper<>();
        //itemWrapper.select("id","order_id","spu_name","sku_name","store_name");
        itemWrapper.eq("order_sn",orderNo);

        List<OmsOrderItem> orderItems = omsOrderItemService.list(itemWrapper);

        omsOrder.setItemEntities(orderItems);



        return R.ok().put("data", omsOrder);
    }



    //点击结算确认订单
    @ApiOperation(value = "根据商品名搜索订单")
    @GetMapping("/searchOrders/{goodsname}")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OmsOrder.class),
    })
    public R searchOrders(@PathVariable("goodsname") String goodsname,HttpServletRequest request) throws ExecutionException, InterruptedException {
        if (StringUtils.isEmpty(goodsname)){
            return R.error().put("msg","商品名关键字不能为空");
        }

        String memberid = JwtUtils.getMemberIdByJwtToken(request);

        //1.查询用户所有订单
        List<OmsOrder> memberorders = omsOrderService.list(new QueryWrapper<OmsOrder>().eq("member_id", memberid));


        //2.根据订单id查询所有订单项
        //2.1收集当前用户订单id
        List<Long> memeberorderids=new ArrayList<>();
        for (OmsOrder order : memberorders) {
            memeberorderids.add(order.getId());
        }
        if (memeberorderids==null || memeberorderids.size()==0){
            R.ok().put("msg","此用户从未购买过商品");
        }

        //2.1根据订单id获取订单项
        QueryWrapper<OmsOrderItem> itemWrapper=new QueryWrapper<>();
        itemWrapper.select("order_id","id","spu_name","sku_name");
        itemWrapper.in("order_id",memeberorderids);

        List<OmsOrderItem> orderItems = omsOrderItemService.list(itemWrapper);

        HashSet<Long> set=new HashSet();
        for (OmsOrderItem item: orderItems) {
            if (!StringUtils.isEmpty(item.getSpuName()) || !StringUtils.isEmpty(item.getSpuName())){
                if (item.getSpuName().contains(goodsname)){
                    set.add(item.getOrderId());
                    continue;
                }
                if (item.getSkuName().contains(goodsname)){
                    set.add(item.getOrderId());
                }
            }
        }

        System.out.println(set);

        List<OmsOrder> finalorders=new ArrayList<>();

        for (OmsOrder order:memberorders){
            if (set.contains(order.getId())){
                finalorders.add(order);
            }
        }


        //System.out.println(orderItems);


        //3.获取每个订单项的订单id，多个订单项的订单id如果相同，做去重


        //4.用去重后的订单id查询订单信息id




        //List<Long> memberordersids= new ArrayList<>();
        //for (OmsOrder order:memberorders){
        //    memberordersids.add(order.getId());
        //}






        List<OmsOrder> orders = omsOrderService.getOrders(finalorders);

        return R.ok().put("data", orders);
    }



    @ApiOperation(value = "购物车---点击结算---确认订单信息")
    @GetMapping("/toTrade")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OrderConfirmVo.class),
    })
    public R toTrade(HttpServletRequest request) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = orderService.confirmOrder(JwtUtils.getMemberIdByJwtToken(request));
        return R.ok().put("data", confirmVo);
    }

    /**
     * 下单功能
     */
    @ApiOperation(value = "订单信息页---提交订单")
    @PostMapping("/submitOrder")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = String.class),
    })
    public R submitOrder(@RequestBody OrderSubmitVo submitVo, HttpServletRequest request) throws Exception {
        SubmitOrderResponseVo responseVo = orderService.submitOrder(submitVo,JwtUtils.getMemberIdByJwtToken(request));
        if (responseVo.getCode()==-1){
            R.error().put("code",500).put("msg","提交订单失败，请不要修改价格");
        }
        return R.ok().put("code",200).put("msg","下单成功").put("orderNo",responseVo.getOrderEntity().getOrderSn());
    }



    @ApiOperation(value = "查看我的订单列表")
    @GetMapping("/getOrders")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OmsOrder.class),
    })
    public R getOrders(HttpServletRequest request) throws ExecutionException, InterruptedException {

        String memberid = JwtUtils.getMemberIdByJwtToken(request);

        List<OmsOrder> orders = omsOrderService.list(new QueryWrapper<OmsOrder>().eq("member_id", memberid).orderByDesc("create_time"));

        for (int i=0;i<orders.size();i++){
            OmsOrder omsOrder = orders.get(i);
            Long orderId = omsOrder.getId();
            List<OmsOrderItem> items = omsOrderItemService.list(new QueryWrapper<OmsOrderItem>().eq("order_id", orderId));

            //查询sku销售属性
            for (int j=0;j<items.size();j++){
                StringBuffer saleString=new StringBuffer("");
                Long skuId = items.get(j).getSkuId();
                List<PmsSkuSaleParamValue> saleList = skuSaleParamValueService.list(new QueryWrapper<PmsSkuSaleParamValue>().eq("sku_id", skuId).orderByAsc("param_id"));
                for (PmsSkuSaleParamValue sale : saleList) {
                    saleString.append(sale.getParamValue()+"  ");
                }
                items.get(j).setSkuAttrsVals(saleString.toString());
            }


            orders.get(i).setItemEntities(items);
        }

        return R.ok().put("data", orders);
    }



    //点击结算确认订单
    @ApiOperation(value = "确认收货")
    @GetMapping("/confirmOrder/{orderNo}")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OmsOrder.class),
    })
    public R confirmOrder(@ApiParam("示例：20210718210218035") @PathVariable("orderNo")String orderNo, HttpServletRequest request) throws ExecutionException, InterruptedException {


        String memberid = JwtUtils.getMemberIdByJwtToken(request);
        OmsOrder order = omsOrderService.getOne(new QueryWrapper<OmsOrder>().eq("member_id", memberid).eq("order_sn", orderNo));
        if (order==null){
            return R.error().put("msg","订单不存在");
        }
        if (order.getPaymentTime()==null){
            return R.error().put("msg","订单还为支付,无法确认收货");
        }
        order.setConfirmStatus(1);
        order.setStatus(3);

        boolean update = omsOrderService.update(order, new QueryWrapper<OmsOrder>().eq("member_id", memberid).eq("order_sn", orderNo));

        if (!update){
            return R.error().put("msg","确认收货失败");
        }

        return R.ok().put("data", order).put("msg","确认收货成功").put("note","确认收货成功，订单的status值修改为3，’我的订单‘页面‘确认收货’按钮可以改为‘已完成’或者’评价‘按钮");
    }




}
